<template>
  <div>
    <el-form ref="formRef" :model="model" :rules="rules" label-width="140px" status-icon>
      <el-form-item label="标题" prop="title">
        <el-input v-model="model.title" />
      </el-form-item>

      <el-form-item label="类型" prop="category_id">
        <el-select v-model="model.category_id" placeholder="请选择" :style="{ width: '300px' }">
          <el-option label="行业新闻" :value="1" />
          <el-option label="企业新闻" :value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="封面" prop="image">
        <uploader
          :key="model"
          :action="uploadApi"
          v-model:value="model.image"
          :width="300"
          :height="150"
        />
      </el-form-item>

      <el-form-item label="推荐" prop="isHome">
        <el-switch v-model="model.isHome" :active-value="1" :inactive-value="0" />
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <editor :key="model" v-model:value="model.content" :height="320" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
const props = defineProps({
  info: { type: Object, default: {} },
})
const formRef = ref(null)
const { VITE_APP_BASE_API, VITE_APP_UPLOAD_URI } = import.meta.env
const uploadApi = VITE_APP_BASE_API + VITE_APP_UPLOAD_URI

const model = ref({
  title: '',
  category_id: 1,
  image: '',
  isHome: 0,
  content: '',
})

const rules = reactive({
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { max: 200, message: '长度不超过200个字符', trigger: 'blur' },
  ],
  image: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
})

onMounted(() => {
  if (props.info) {
    model.value = JSON.parse(JSON.stringify(props.info))
  }
})

const submit = (updateApi, form) => {
  if (!form) return
  if (model.value.content === '<p><br></p>') {
    model.value.content = ''
  }
  return form.validate(async (valid, fields) => {
    if (!valid) {
      for (let item in fields) {
        ElMessage.error(fields[item][0].message)
      }
      return false
    }
    const { code } = await updateApi(model.value)
    if (code === 200) {
      ElMessage.success('添加成功')
      return true
    }
  })
}

defineExpose({ submit, formRef })
</script>
